//
//  NCSecondaryFilterTableView.swift
//  FilterBox
//
//  Created by 张文晏 on 2018/11/9.
//  Copyright © 2018 张文晏. All rights reserved.
//

import UIKit

public class NCSecondaryFilterTableView: UIView, NCFilterTable {
    public var filterBox: NCFilterBox?
    
    public var filterTabButton: NCFilterTabButton?
    
    public var isMultiSelection: Bool = false
    
    typealias sectionItems = [NCFilterBox.IdNameItem]
    @IBOutlet weak var mainTableView: UITableView!
    @IBOutlet weak var secondaryTableView: UITableView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet var bottomView: NCFilterBottomView!
    @IBOutlet weak var constraintContentViewTop: NSLayoutConstraint!
    
    func reset() {
        selectedItems = selectedItems.map({ (items) -> [NCFilterBox.IdNameItem] in
            items.map({ (item) -> NCFilterBox.IdNameItem in
                return NCFilterBox.IdNameItem(id: 0, name: "")
            })
        })
        secondaryTableView.reloadData()
    }
    
    func confrim() {
        selectedClosure?(selectedItems)
        hide()
    }
    
    @IBAction func clickBg(_ sender: Any) {
        hide()
    }
    
    lazy var searchHeader = NCFilterBoxSearchHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width/2, height: 44))
    
    private var items = [sectionItems]()
    private var sectionNames = [String]()
    
    public var selectedItems = [[NCFilterBox.IdNameItem]]()
    var currentSection = 0
    
    public var selectedClosure:((_ items:[[NCFilterBox.IdNameItem]])->())?
    
    
    public var isShowSearchHeader = false{
        didSet {
            if isShowSearchHeader {
                searchHeader.backgroundColor = UIColor(hex: 0xf4f4f4)
                secondaryTableView.tableHeaderView = searchHeader
            }
        }
    }
    
    public init() {
        super.init(frame: CGRect.init(x: 0, y: 44, width: 375, height: 600))
        _ = fromNib()
        bottomView.resetClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.reset()
        }
        bottomView.confirmClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.confrim()
        }
        mainTableView.register(UITableViewCell.self, forCellReuseIdentifier: "FilterMainTableViewCell")
        mainTableView.delegate = self
        mainTableView.dataSource = self
        
        let bundle = Bundle.init(for: self.classForCoder)
        secondaryTableView.register(UINib.init(nibName: "NCFilterTableViewCell", bundle: bundle), forCellReuseIdentifier: "NCFilterTableViewCell")
        secondaryTableView.delegate = self
        secondaryTableView.dataSource = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func set(items: [[NCFilterBox.IdNameItem]]){
        self.items = items
        selectedItems = Array<[NCFilterBox.IdNameItem]>.init(repeating: Array<NCFilterBox.IdNameItem>.init(), count: items.count)
    }
    
    public func set(sectionNames: [String]){
        self.sectionNames = sectionNames
    }
    
    public func search(_ searchClosure: ((_ text: String?)->())?){
        searchHeader.searchClosure = searchClosure
    }
    
    public func show(){
        guard let box = filterBox, let owner = box.owner else { return }
        owner.view.insertSubview(self, belowSubview: box.tabButtonContainer)
        self.frame = CGRect.init(x: 0, y: 44, width: owner.view.bounds.width, height: owner.view.bounds.height - 44)
        mainTableView.reloadData()
        secondaryTableView.reloadData()
        
        constraintContentViewTop.constant = -contentView.bounds.height
        layoutIfNeeded()
        constraintContentViewTop.constant = 0
        UIView.animate(withDuration: 0.3) {
            self.layoutIfNeeded()
        }
    }
    
    public func hide(){
        filterTabButton?.isSelected = false
        constraintContentViewTop.constant = -contentView.bounds.height
        UIView.animate(withDuration: 0.3, animations: {
            self.layoutIfNeeded()
        }) { (_) in
            self.removeFromSuperview()
        }
        
    }
    
    
}

extension NCSecondaryFilterTableView: UITableViewDelegate, UITableViewDataSource{
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == mainTableView{
            return items.count
        }else{
            return items[currentSection].count
        }
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == mainTableView{
            let cell = tableView.dequeueReusableCell(withIdentifier: "FilterMainTableViewCell", for: indexPath)
            cell.selectionStyle = .none
            cell.textLabel?.text = sectionNames[indexPath.row]
            cell.backgroundColor = indexPath.row == currentSection ? UIColor.init(hex:0xf4f4f4) : .white
            cell.textLabel?.textColor = indexPath.row == currentSection ? UIColor.init(hex:0x006fff) : UIColor.init(hex:0x333333)
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "NCFilterTableViewCell", for: indexPath) as! NCFilterTableViewCell
            cell.selectionStyle = .none
            cell.backgroundColor = UIColor.init(hex:0xf4f4f4)
            cell.beSelected = selectedItems[currentSection].contains(where: {$0.id == items[currentSection][indexPath.row].id})
            cell.isMultiSelection = true
            cell.title = items[currentSection][indexPath.row].name
            return cell
        }
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == mainTableView{
            currentSection = indexPath.row
            mainTableView.reloadData()
            secondaryTableView.reloadData()
        }else{
            let item = items[currentSection][indexPath.row]
            if let idx = selectedItems[currentSection].index(where: { $0.id == item.id}){
                selectedItems[currentSection].remove(at: idx)
            }else{
                selectedItems[currentSection].append(item)
            }
            secondaryTableView.reloadData()
        }
    }
}
